package at.codebase.web.servlets.migration;

import java.util.List;

import org.json.simple.JSONObject;

import at.codebase.db.dao.EItemDao;
import at.codebase.db.dao.EUserDao;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EUser;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.json.JsonDecoder;
import at.codebase.web.util.servlet.ApiSecureServlet;

public class UserImport extends ApiSecureServlet {

	@Override
	protected JSONObject processRequest(RequestInformation requestInfo, String authToken) {
			try {
				String userDataString = requestInfo.getParameters().getString("user_data");
				log.severe(userDataString);
				
				
				EUser user = JsonDecoder.decodeUser(userDataString);
				
				if(user.getUsername() == null || user.getUsername().trim().equals("")){
					return badRequestResult("Username is invalid");
				}
				if(user.getGoogleUserId() == null || user.getGoogleUserId().trim().equals("")){
					return badRequestResult("GoogleUserId is invalid");
				}
				if(user.getMail() == null || user.getMail().trim().equals("")){
					return badRequestResult("Mail is invalid");
				}
				
				// User already exists in our application
				if(EUserDao.getUserByGoogleId(user.getGoogleUserId()) != null) {
					return badRequestResult("User already exists");
				}
				
				if(EUserDao.duplicateUsername(user.getUsername())){
					return badRequestResult("Username already exists");
				}
				EUserDao.saveUser(user);
				List<EItem> items = JsonDecoder.decodeUserItems(userDataString);
				for (EItem item : items) {
					item.setSeller(EUser.ref(user));
					EItemDao.saveItem(item);
				}
			} catch (ParameterDoesNotExistException e) {
				return badRequestResult("Missing parameter \"user_data\"");
			}
			return successResult();
	}

}
